//
//  WCGroup.m
//  WabbitCode
//
//  Created by William Towe on 1/28/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCGroup.h"
#import "WCMacros.h"
#import "WCProject.h"
#import "WCTextFile.h"
#import "WCAppController.h"
#import "NSImage+WCExtensions.h"
#import "NSTreeNode+WCExtensions.h"


NSString *kWCGroupUnableToInsertAbsoluteFilePathKey = @"kWCGroupUnableToInsertAbsoluteFilePathKey";
NSString *kWCGroupUnableToInsertReasonKey = @"kWCGroupUnableToInsertReasonKey";

static NSFileManager *fm = nil;
static NSWorkspace *sw = nil;

@interface WCGroup (Private)
- (void)_addChildPathsWithEncodingType:(NSStringEncoding)encodingType;
@end


@implementation WCGroup
#pragma mark *** Subclass Overrides ***
+ (void)initialize {
	fm = [NSFileManager defaultManager];
	sw = [NSWorkspace sharedWorkspace];
}

- (NSImage *)icon {
	return [NSImage imageNamed:@"Group16x16"];
}

- (BOOL)isLeaf {
	return NO;
}

- (NSString *)folderPath {
	return [self absoluteFilePath];
}

- (NSString *)name {
	return _name;
}

- (void)setName:(NSString *)value {
	if (_name == value)
		return;
	
	[_name release];
	_name = [value copy];
}

- (BOOL)canUngroupNode {
	return YES;
}

- (NSArray *)acceptedDropTypes {
	static NSArray *types = nil;
	if (!types)
		types = [[NSArray alloc] initWithObjects:[WCGroup class], [WCFile class], [WCTextFile class], nil];
	return types;
}

- (Class)commonClass {
	return [self superclass];
}

- (id)initWithFilePath:(NSString *)filePath inProject:(WCProject *)project; {
	return [self initWithFilePath:filePath name:[filePath lastPathComponent] inProject:project];
}
#pragma mark *** Public Methods ***
// returns the new top level model objects that were added
- (NSArray *)insertFilePaths:(NSArray *)filePaths atIndex:(NSUInteger)index copyFiles:(BOOL)flag usingEncoding:(NSStringEncoding)encoding; {
	NSMutableArray *newItems = [NSMutableArray array];
	BOOL isDirectory = NO;
	NSSet *currentFilePaths = [NSSet setWithArray:[[[[self project] projectGroup] descendantNodes] valueForKey:@"absoluteFilePath"]];
	filePaths = [filePaths sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"lastPathComponent" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]]];
	
	for (NSString *filePath in filePaths) {
		NSString *newPath = (flag)?[[self folderPath] stringByAppendingPathComponent:[filePath lastPathComponent]]:filePath;
		
		// don't add the file if it already exists in the project
		if ([currentFilePaths containsObject:newPath])
			continue;
		
		// attempt to copy the file
		if (![[NSFileManager defaultManager] fileExistsAtPath:newPath isDirectory:&isDirectory] && flag) {
			// skip the current file if it could not be copied
			NSError *error = nil;
			if (![[NSFileManager defaultManager] copyItemAtPath:filePath toPath:newPath error:&error]) {
				newPath = filePath;
			}
		}
		
		id item = nil;
		
		if (isDirectory) {
			item = [WCGroup groupWithFilePath:newPath inProject:[self project]];
			NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
			[item recursivelyAddFilePathsFromFolderPath:newPath usingEncoding:encoding];
			[pool release];
		}
		else if ([kWCDocumentFileExtensions containsObject:[filePath pathExtension]]) {
			item = [WCTextFile textFileWithFilePath:newPath fileEncoding:encoding inProject:_project];
		}
		else {
			item = [WCFile fileWithFilePath:newPath inProject:_project];
		}
		
		[[self mutableChildNodes] insertObject:item atIndex:index++];
		[newItems addObject:item];
	}
	return [[newItems copy] autorelease];
}

- (void)recursivelyAddFilePathsFromFolderPath:(NSString *)folderPath; {
	[self recursivelyAddFilePathsFromFolderPath:folderPath usingEncoding:NSUserDefaultsUnsignedIntegerForKey(kWCPrefsEditorDefaultFileEncodingKey)];
}

- (void)recursivelyAddFilePathsFromFolderPath:(NSString *)folderPath usingEncoding:(NSStringEncoding)encoding; {
	BOOL isDirectory = NO;
	
	for (NSString *fileName in [[[NSFileManager defaultManager] directoryContentsAtPath:folderPath] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"lastPathComponent" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]]]) {
		NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
		
		if ([fileName hasPrefix:@"."])
			continue;
		else if ([fileName isEqualToString:@"build"])
			continue;
		else if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filePath])
			continue;
		
		id node = nil;
		
		if ([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
			node = [WCGroup groupWithFilePath:filePath inProject:[self project]];
			[node recursivelyAddFilePathsFromFolderPath:filePath usingEncoding:encoding];
			if ([[node descendantLeafNodes] count])
				[[self mutableChildNodes] addObject:node];
		}
		else if ([kWCDocumentFileExtensions containsObject:[fileName pathExtension]]) {
			node = [WCTextFile textFileWithFilePath:filePath fileEncoding:encoding inProject:[self project]];
			[[self mutableChildNodes] addObject:node];
		}
		else {
			node = [WCFile fileWithFilePath:filePath inProject:[self project]];
			[[self mutableChildNodes] addObject:node];
		}
	}
}
#pragma mark Accessors


#pragma mark Creation

+ (id)groupWithFilePath:(NSString *)filePath inProject:(WCProject *)project; {
	return [[[[self class] alloc] initWithFilePath:filePath inProject:project] autorelease];
}
+ (id)groupWithFilePath:(NSString *)filePath name:(NSString *)name inProject:(WCProject *)project; {
	return [[[[self class] alloc] initWithFilePath:filePath name:name inProject:project] autorelease];
}

#pragma mark *** Private Methods ***
- (BOOL)_addChildPathsWithEncodingType:(NSStringEncoding)encodingType errorDictionaries:(NSMutableArray **)dicts; {
	
	return YES;
}


@end
